package com.ys.erp.common.util;

import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

;

/**
 * @author lwj
 * @date 2021/5/7
 */
@Data
public class EncryptionUtil {

    private static final String AES_ALGORITHM = "AES";
    private static final String FINANCE_KEY = "bY8|lV7]fX8<qD7?fA5;iK7<";

    /**
     * 生成uuid
     *
     * @return uuid
     */
    public static String generateUuid() {
        return UUID.randomUUID().toString();
    }

    public static String getUuidOnlyStr() {
        return UUID.randomUUID().toString()
                .replaceAll("-", "")
                .toUpperCase();
    }

    /**
     * MD5 加盐 加密
     *
     * @param salt salt
     * @param data data
     * @return 加密信息
     */
    public static String md5Encryption(String data, String salt) {
        String s = data + salt;
        return md5Encryption(s);
    }

    /**
     * MD5加密
     *
     * @param data data
     * @return 加密信息
     */
    public static String md5Encryption(String data) {
        return org.springframework.util.DigestUtils.md5DigestAsHex(data.getBytes()).toLowerCase();
    }

    public static String encryptMd5UTF_8(String string) {
        try {
            return encryptMd5(string, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptMd5(String string, String charSet) throws UnsupportedEncodingException {
        return DigestUtils.md5Hex(string.getBytes(charSet));
    }

    public static String aesEncrypt(String data, String key) throws Exception {
        if (ObjectUtils.isEmpty(key)) {
            key = FINANCE_KEY;
        }
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String aesDecrypt(String encryptedData, String key) throws Exception {
        if (ObjectUtils.isEmpty(key)) {
            key = FINANCE_KEY;
        }
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

}
